package br.com.rapidrest.util;

import java.util.Arrays;
import java.util.regex.Pattern;

import br.com.rapidrest.request.RequestScope;

public class RequestScopeBuilder {

	private static final Pattern SPLIT_REGEX = Pattern.compile("/");

	public static RequestScope build(String uri, String webPackage) {
		RequestScope requestScope = new RequestScope();

		uri = uri.substring(1);

		String[] paths = SPLIT_REGEX.split(uri);

		StringBuilder classNameBuilder = new StringBuilder(webPackage);

		final String dot = ".";
		int index = 0;
		for (; index < paths.length; index++) {
			String path = paths[index];
			if (Character.isUpperCase(path.charAt(0))) {
				int firstIndexOf = path.indexOf(dot);
				if (firstIndexOf > 0) {
					String methodName = path.substring(firstIndexOf + 1);
					requestScope.setMethodName(methodName);
					path = path.substring(0, firstIndexOf);
				}
				classNameBuilder.append(dot).append(path);
				break;
			}
			classNameBuilder.append(dot).append(path);
		}

		try {
			Class<?> beanClass = Class.forName(classNameBuilder.toString());
			requestScope.setBeanClass(beanClass);
		} catch (ClassNotFoundException e) {
			return null;
		}

		if (index + 1 < paths.length) {
			String[] params = Arrays
					.copyOfRange(paths, index + 1, paths.length);

			requestScope.setParams(params);
		}

		return requestScope;
	}

}
